<template>
  <el-dialog
    v-model="dialogVisible"
    title="短信模板管理"
    width="1000px"
    :close-on-click-modal="false"
  >
    <div class="template-management">
      <!-- 工具栏 -->
      <div class="toolbar">
        <div class="toolbar-left">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增模板
          </el-button>
          <el-button @click="handleBatchDelete" :disabled="!selectedTemplates.length">
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
          <el-button @click="handleImport">
            <el-icon><Upload /></el-icon>
            导入模板
          </el-button>
          <el-button @click="handleExport">
            <el-icon><Download /></el-icon>
            导出模板
          </el-button>
        </div>
        
        <div class="toolbar-right">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索模板名称或内容"
            style="width: 250px"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          
          <el-select v-model="categoryFilter" placeholder="模板分类" style="width: 120px" clearable>
            <el-option label="全部" value="" />
            <el-option label="通知类" value="notification" />
            <el-option label="验证码" value="verification" />
            <el-option label="营销类" value="marketing" />
            <el-option label="告警类" value="alarm" />
          </el-select>
          
          <el-select v-model="statusFilter" placeholder="状态" style="width: 100px" clearable>
            <el-option label="全部" value="" />
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </div>
      </div>

      <!-- 模板列表 -->
      <el-table
        ref="tableRef"
        :data="filteredTemplates"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="模板名称" width="150" show-overflow-tooltip />
        <el-table-column prop="category" label="分类" width="100">
          <template #default="{ row }">
            <el-tag :type="getCategoryTagType(row.category)" size="small">
              {{ getCategoryText(row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="模板内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="variables" label="变量" width="120">
          <template #default="{ row }">
            <el-tag
              v-for="variable in row.variables"
              :key="variable"
              size="small"
              style="margin-right: 5px"
            >
              {{ variable }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="usageCount" label="使用次数" width="100" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              active-value="active"
              inactive-value="inactive"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" link @click="handlePreview(row)">
              预览
            </el-button>
            <el-button type="success" size="small" link @click="handleUse(row)">
              使用
            </el-button>
            <el-button type="warning" size="small" link @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="info" size="small" link @click="handleCopy(row)">
              复制
            </el-button>
            <el-button type="danger" size="small" link @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="filteredTemplates.length"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </div>
    </template>

    <!-- 模板表单对话框 -->
    <el-dialog
      v-model="templateFormVisible"
      :title="isEditTemplate ? '编辑模板' : '新增模板'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="templateFormRef"
        :model="templateForm"
        :rules="templateFormRules"
        label-width="100px"
      >
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="templateForm.name" placeholder="请输入模板名称" />
        </el-form-item>
        
        <el-form-item label="模板分类" prop="category">
          <el-select v-model="templateForm.category" placeholder="请选择分类" style="width: 100%">
            <el-option label="通知类" value="notification" />
            <el-option label="验证码" value="verification" />
            <el-option label="营销类" value="marketing" />
            <el-option label="告警类" value="alarm" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="模板内容" prop="content">
          <el-input
            v-model="templateForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入模板内容，使用{变量名}表示变量"
            maxlength="500"
            show-word-limit
          />
          <div class="form-tip">
            使用 {变量名} 的格式定义变量，如：{name}、{code}、{time} 等
          </div>
        </el-form-item>
        
        <el-form-item label="变量说明">
          <div class="variables-info">
            <div
              v-for="variable in extractedVariables"
              :key="variable"
              class="variable-item"
            >
              <el-tag size="small">{{ variable }}</el-tag>
              <el-input
                v-model="variableDescriptions[variable]"
                placeholder="变量说明"
                size="small"
                style="width: 200px; margin-left: 10px"
              />
            </div>
            <div v-if="!extractedVariables.length" class="no-variables">
              暂无变量
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="模板描述" prop="description">
          <el-input
            v-model="templateForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入模板描述（可选）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="templateForm.status">
            <el-radio value="active">启用</el-radio>
            <el-radio value="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="templateFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveTemplate" :loading="saveLoading">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 模板预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="模板预览"
      width="500px"
    >
      <div class="template-preview">
        <div class="preview-info">
          <div><strong>模板名称：</strong>{{ previewTemplate.name }}</div>
          <div><strong>模板分类：</strong>{{ getCategoryText(previewTemplate.category) }}</div>
          <div><strong>使用次数：</strong>{{ previewTemplate.usageCount }}</div>
        </div>
        
        <div class="preview-content">
          <div class="content-label">模板内容：</div>
          <div class="content-text">{{ previewTemplate.content }}</div>
        </div>
        
        <div v-if="previewTemplate.variables?.length" class="preview-variables">
          <div class="variables-label">变量列表：</div>
          <div class="variables-list">
            <el-tag
              v-for="variable in previewTemplate.variables"
              :key="variable"
              size="small"
              style="margin-right: 8px; margin-bottom: 8px"
            >
              {{ variable }}
            </el-tag>
          </div>
        </div>
        
        <div class="preview-example">
          <div class="example-label">示例效果：</div>
          <div class="example-content">{{ getExampleContent(previewTemplate) }}</div>
        </div>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Upload, Download, Search } from '@element-plus/icons-vue'

interface Props {
  visible: boolean
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'use-template', template: any): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false
})

const emit = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 表格引用
const tableRef = ref()
const templateFormRef = ref()

// 搜索和过滤
const searchKeyword = ref('')
const categoryFilter = ref('')
const statusFilter = ref('')

// 分页
const currentPage = ref(1)
const pageSize = ref(20)

// 选中的模板
const selectedTemplates = ref([])

// 模板表单对话框
const templateFormVisible = ref(false)
const isEditTemplate = ref(false)
const saveLoading = ref(false)

// 预览对话框
const previewVisible = ref(false)
const previewTemplate = ref({})

// 模板表单数据
const templateForm = reactive({
  id: '',
  name: '',
  category: '',
  content: '',
  description: '',
  status: 'active'
})

// 变量描述
const variableDescriptions = ref({})

// 模板列表（模拟数据）
const templates = ref([
  {
    id: 1,
    name: '验证码模板',
    category: 'verification',
    content: '您的验证码是{code}，请在{minutes}分钟内使用。',
    variables: ['{code}', '{minutes}'],
    description: '用于发送验证码的通用模板',
    usageCount: 1250,
    status: 'active',
    createTime: '2024-01-10 09:00:00'
  },
  {
    id: 2,
    name: '系统维护通知',
    category: 'notification',
    content: '系统将于{time}进行维护，预计持续{duration}，请提前做好准备。',
    variables: ['{time}', '{duration}'],
    description: '系统维护时的通知模板',
    usageCount: 85,
    status: 'active',
    createTime: '2024-01-08 14:30:00'
  },
  {
    id: 3,
    name: '水位告警',
    category: 'alarm',
    content: '{reservoir}水库水位已达到{level}米，超过警戒线{warning_level}米，请立即采取相应措施。',
    variables: ['{reservoir}', '{level}', '{warning_level}'],
    description: '水位超过警戒线时的告警模板',
    usageCount: 42,
    status: 'active',
    createTime: '2024-01-05 16:20:00'
  },
  {
    id: 4,
    name: '会议提醒',
    category: 'notification',
    content: '您好{name}，提醒您{date}在{location}参加{meeting}会议。',
    variables: ['{name}', '{date}', '{location}', '{meeting}'],
    description: '会议提醒通知模板',
    usageCount: 156,
    status: 'active',
    createTime: '2024-01-03 11:15:00'
  },
  {
    id: 5,
    name: '营销推广',
    category: 'marketing',
    content: '尊敬的{name}，我们的{product}正在促销，优惠{discount}，详情请访问{url}',
    variables: ['{name}', '{product}', '{discount}', '{url}'],
    description: '产品营销推广模板',
    usageCount: 0,
    status: 'inactive',
    createTime: '2024-01-01 10:00:00'
  }
])

// 过滤后的模板列表
const filteredTemplates = computed(() => {
  let filtered = templates.value

  if (searchKeyword.value) {
    filtered = filtered.filter(item =>
      item.name.includes(searchKeyword.value) ||
      item.content.includes(searchKeyword.value)
    )
  }

  if (categoryFilter.value) {
    filtered = filtered.filter(item => item.category === categoryFilter.value)
  }

  if (statusFilter.value) {
    filtered = filtered.filter(item => item.status === statusFilter.value)
  }

  return filtered
})

// 从模板内容中提取变量
const extractedVariables = computed(() => {
  const matches = templateForm.content.match(/\{[^}]+\}/g)
  return matches ? [...new Set(matches)] : []
})

// 表单验证规则
const templateFormRules = {
  name: [
    { required: true, message: '请输入模板名称', trigger: 'blur' },
    { min: 2, max: 50, message: '模板名称长度在2-50个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择模板分类', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入模板内容', trigger: 'blur' },
    { min: 1, max: 500, message: '模板内容长度在1-500个字符', trigger: 'blur' }
  ]
}

// 获取分类标签类型
const getCategoryTagType = (category: string) => {
  const types: Record<string, string> = {
    notification: 'primary',
    verification: 'success',
    marketing: 'warning',
    alarm: 'danger'
  }
  return types[category] || 'primary'
}

// 获取分类文本
const getCategoryText = (category: string) => {
  const texts: Record<string, string> = {
    notification: '通知类',
    verification: '验证码',
    marketing: '营销类',
    alarm: '告警类'
  }
  return texts[category] || category
}

// 处理选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedTemplates.value = selection
}

// 新增模板
const handleAdd = () => {
  isEditTemplate.value = false
  resetTemplateForm()
  templateFormVisible.value = true
}

// 编辑模板
const handleEdit = (template: any) => {
  isEditTemplate.value = true
  Object.assign(templateForm, template)
  templateFormVisible.value = true
}

// 复制模板
const handleCopy = (template: any) => {
  isEditTemplate.value = false
  Object.assign(templateForm, {
    ...template,
    id: '',
    name: template.name + ' - 副本'
  })
  templateFormVisible.value = true
}

// 删除模板
const handleDelete = async (template: any) => {
  try {
    await ElMessageBox.confirm(`确认删除模板"${template.name}"？`, '确认删除')
    
    const index = templates.value.findIndex(item => item.id === template.id)
    if (index > -1) {
      templates.value.splice(index, 1)
    }
    
    ElMessage.success('删除成功')
  } catch (error) {
    // 用户取消
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(`确认删除选中的${selectedTemplates.value.length}个模板？`, '确认删除')
    
    const selectedIds = selectedTemplates.value.map((item: any) => item.id)
    templates.value = templates.value.filter(item => !selectedIds.includes(item.id))
    
    ElMessage.success('批量删除成功')
    selectedTemplates.value = []
  } catch (error) {
    // 用户取消
  }
}

// 状态变化
const handleStatusChange = (template: any) => {
  ElMessage.success(`模板"${template.name}"状态已更新`)
}

// 预览模板
const handlePreview = (template: any) => {
  previewTemplate.value = template
  previewVisible.value = true
}

// 使用模板
const handleUse = (template: any) => {
  emit('use-template', template)
  dialogVisible.value = false
  ElMessage.success(`已选择模板"${template.name}"`)
}

// 导入模板
const handleImport = () => {
  ElMessage.info('导入功能开发中...')
}

// 导出模板
const handleExport = () => {
  ElMessage.success('模板导出成功')
}

// 保存模板
const handleSaveTemplate = async () => {
  try {
    await templateFormRef.value?.validate()
    saveLoading.value = true
    
    // 模拟保存
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (isEditTemplate.value) {
      // 编辑
      const index = templates.value.findIndex(item => item.id === templateForm.id)
      if (index > -1) {
        Object.assign(templates.value[index], {
          ...templateForm,
          variables: extractedVariables.value
        })
      }
      ElMessage.success('模板更新成功')
    } else {
      // 新增
      const newTemplate = {
        ...templateForm,
        id: Date.now(),
        variables: extractedVariables.value,
        usageCount: 0,
        createTime: new Date().toLocaleString()
      }
      templates.value.unshift(newTemplate)
      ElMessage.success('模板创建成功')
    }
    
    templateFormVisible.value = false
    resetTemplateForm()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    saveLoading.value = false
  }
}

// 重置模板表单
const resetTemplateForm = () => {
  templateFormRef.value?.resetFields()
  Object.assign(templateForm, {
    id: '',
    name: '',
    category: '',
    content: '',
    description: '',
    status: 'active'
  })
  variableDescriptions.value = {}
}

// 获取示例内容
const getExampleContent = (template: any) => {
  let content = template.content
  
  // 替换常见变量为示例值
  const examples: Record<string, string> = {
    '{code}': '123456',
    '{minutes}': '5',
    '{time}': '2024-01-15 02:00',
    '{duration}': '2小时',
    '{name}': '张三',
    '{date}': '2024-01-15',
    '{location}': '会议室A',
    '{meeting}': '月度工作会议',
    '{reservoir}': '某某',
    '{level}': '125.5',
    '{warning_level}': '120.0',
    '{product}': '智能水库管理系统',
    '{discount}': '8折',
    '{url}': 'https://example.com'
  }
  
  Object.entries(examples).forEach(([variable, value]) => {
    content = content.replace(new RegExp(variable.replace(/[{}]/g, '\\$&'), 'g'), value)
  })
  
  return content
}
</script>

<style scoped>
.template-management {
  height: 600px;
  display: flex;
  flex-direction: column;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.toolbar-left {
  display: flex;
  gap: 10px;
}

.toolbar-right {
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.variables-info {
  border: 1px solid #e9ecef;
  border-radius: 4px;
  padding: 10px;
  background-color: #f8f9fa;
}

.variable-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.variable-item:last-child {
  margin-bottom: 0;
}

.no-variables {
  text-align: center;
  color: #999;
  font-size: 12px;
}

.template-preview {
  padding: 10px 0;
}

.preview-info {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e9ecef;
}

.preview-info div {
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.preview-content {
  margin-bottom: 20px;
}

.content-label {
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.content-text {
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e9ecef;
  font-size: 14px;
  line-height: 1.6;
  white-space: pre-wrap;
}

.preview-variables {
  margin-bottom: 20px;
}

.variables-label {
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.variables-list {
  display: flex;
  flex-wrap: wrap;
}

.preview-example {
  margin-bottom: 10px;
}

.example-label {
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.example-content {
  padding: 12px;
  background-color: #e8f5e8;
  border-radius: 4px;
  border: 1px solid #b3d8b3;
  font-size: 14px;
  line-height: 1.6;
  color: #2d5a2d;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-table) {
  flex: 1;
  font-size: 13px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-tag) {
  margin-right: 5px;
}
</style>